package com.kedacom.testlego.view.activity

import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.widget.MediaController
import com.kedacom.lego.annotation.ContentView
import com.kedacom.lego.annotation.Extra
import com.kedacom.lego.annotation.ViewModel
import com.kedacom.testlego.R
import com.kedacom.testlego.constant.TrustAllHostnameVerifier
import com.kedacom.testlego.databinding.ActivityVideoViewBinding
import com.kedacom.testlego.viewmodel.BaseViewModel
import com.kedacom.widget.util.Utils
import java.lang.RuntimeException
import java.security.SecureRandom
import java.security.cert.X509Certificate
import javax.net.ssl.*


/**
 *@describe:使用VideoView进行播放
 *@version:
 *@author: tangqi
 *@since: 2020/12/30 AND 15:29
 */
@ContentView(R.layout.activity_video_view)
@ViewModel(BaseViewModel::class)
class VideoPlayActivity : BaseActivity<ActivityVideoViewBinding, BaseViewModel>() {

    @Extra("videoUrl")
    var videoPath: String = "" //视频路径

    @Extra("videoName")
    var videoName: String = "" //视频名称


    fun getUnsafeSslSocketFactory(): SSLSocketFactory? {
        return try {
            val trustAllCerts = arrayOf<TrustManager>(
                object : X509TrustManager {
                    override fun checkClientTrusted(
                        chain: Array<X509Certificate>,
                        authType: String
                    ) {
                    }

                    override fun checkServerTrusted(
                        chain: Array<X509Certificate>,
                        authType: String
                    ) {
                    }

                    override fun getAcceptedIssuers(): Array<X509Certificate> {
                        return arrayOf()
                    }
                }
            )
            val sslContext = SSLContext.getInstance("SSL")
            sslContext.init(null, trustAllCerts, SecureRandom())
            sslContext.socketFactory
        } catch (e: java.lang.Exception) {
            throw RuntimeException(e)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 支持HTTPS
        HttpsURLConnection.setDefaultSSLSocketFactory(getUnsafeSslSocketFactory())
        var defaultHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier()
        if(defaultHostnameVerifier == null
            || !(defaultHostnameVerifier is TrustAllHostnameVerifier)){
            HttpsURLConnection.setDefaultHostnameVerifier(TrustAllHostnameVerifier())
        }


        showLoading("视频加载中....")

        if (videoPath.isNullOrEmpty()) {
            finish()
            showToast("缺少视频地址")
            return
        }

        /**
         * 设置播放的资源路径，使用 setVideoURI(Uri uri)  或者 setVideoPath(String path)(底层也是调用的  serVideoURL(Uri uri))
         */
//        nViewDataBinding.videoView.setVideoPath(url)
        nViewDataBinding.videoView.setVideoURI(Uri.parse(videoPath))

        /**为控件设置焦点 */
        nViewDataBinding.videoView.requestFocus()


        /**
         * 为 VideoView 视图设置媒体控制器，设置了之后就会自动由进度条、前进、后退等操作
         */
        nViewDataBinding.videoView.setMediaController(MediaController(this))


        /**视频准备完成时回调
         */
        nViewDataBinding.videoView.setOnPreparedListener {
            Log.i("tag", "--------------视频准备完毕,可以进行播放.......")
            hideLoading()
        }

        /**
         * 视频播放完成时回调
         */
        nViewDataBinding.videoView.setOnCompletionListener {
            Log.i(
                "tag",
                "------------------视频播放完毕.........."
            )
            finish()
        }


        /**
         * 视频播放发送错误时回调
         */
        nViewDataBinding.videoView.setOnErrorListener { mp, what, extra ->
            Log.i("tag", "---------------------视频播放失败...........")
            hideLoading()
            false
        }
        nViewDataBinding.videoView.start()

//        playVideo(videoPath)
    }

//    private fun playVideo(videoPath: String) {
//        if (!TextUtils.isEmpty(videoPath)) {
//            LegoLog.d(" qqvideoPath $videoPath")
//            val referer = getReferer(videoPath)
//            if (TextUtils.isEmpty(referer)) {
//                showToast("播放器地址非法 含有空格!")
//            }
//            val mapHeadData: MutableMap<String?, String?> = HashMap()
//            mapHeadData["Referer"] = referer
//            val temp = videoPath.replace("https", "http")
//            setVideoPath(temp, mapHeadData)
//            nViewDataBinding.videoView.start()
//        }
//    }
//
//    fun setVideoPath(path: String, headerMap: Map<String?, String?>) {
//        if (headerMap.isEmpty()) {
//            nViewDataBinding.videoView.setVideoURI(Uri.parse(path))
//        } else {
//            nViewDataBinding.videoView.setVideoURI(Uri.parse(path), headerMap)
//        }
//    }
//
//    /**
//     * 获取当前域名的地址以及端口号
//     *
//     * @param path
//     * @return
//     */
//    private fun getReferer(path: String): String {
//        val tempPath = path.trim { it <= ' ' }
//        if (tempPath != null && tempPath.contains(" ")) {
//            return ""
//        }
//        val uri = URI.create(tempPath)
//        var effectiveURI: URI? = null
//        try {
//            effectiveURI = URI(uri.scheme, uri.userInfo, uri.host, uri.port, null, null, null)
//            return effectiveURI.toString()
//        } catch (var4: Exception) {
//            effectiveURI = null
//            LegoLog.d("onDemandDetailActivity exception")
//        }
//        return " "
//    }


    override fun onDestroy() {
        super.onDestroy()
        nViewDataBinding.videoView.clearFocus()
        nViewDataBinding.videoView.stopPlayback()
    }

    override fun onBackPressed() {
        finish()
    }

}